package com.mf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mf.entity.User;
import com.mf.entity.UserTransferRecord;
import com.mf.enums.InAndOutEnum;
import com.mf.exceptions.GraceException;
import com.mf.mapper.UserMapper;
import com.mf.mapper.UserTransferRecordMapper;

import com.mf.service.IUserTransferRecordService;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
* <p>
    * 转账记录 服务实现类
    * </p>
*
* @author mf
* @since 2024-06-08
*/
@Service
public class UserTransferRecordServiceImpl extends ServiceImpl<UserTransferRecordMapper, UserTransferRecord> implements IUserTransferRecordService {
    @Resource
    private UserTransferRecordMapper userTransferRecordMapper;

    @Resource
    private UserMapper userMapper;

    /**
     * 新增转账记录
     */
    @Override
    @Transactional
    public void add(UserTransferRecord userTransferRecord) {
        final User user = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getId, userTransferRecord.getUserId()));
        // 判断转出金额是否超过用户持有金额
        if (userTransferRecord.getType().equals(InAndOutEnum.OUT.status)) {
            // 转出不能转出金额超过用户持有金额
            if (user.getAmount().compareTo(userTransferRecord.getAmount()) < 0) {
                GraceException.display("转出金额超过用户持有金额");
            }
            user.setAmount(user.getAmount().subtract(userTransferRecord.getAmount()));
        }else {
            user.setAmount(user.getAmount().add(userTransferRecord.getAmount()));
        }
        userMapper.updateById(user);
        userTransferRecordMapper.insert(userTransferRecord);
    }

    /**
     * 根据用户id查询
     */
    @Override
    @Transactional
    public List<UserTransferRecord> findByUserId(Integer userId) {
        final LambdaQueryWrapper<UserTransferRecord> queryWrapper = new LambdaQueryWrapper<UserTransferRecord>()
                .eq(UserTransferRecord::getUserId, userId)
                .orderByDesc(UserTransferRecord::getCreatedTime);
        return userTransferRecordMapper.selectList(queryWrapper);
    }
}
